<?php
// +----------------------------------------------------------------------
// | 敦煌网卖家发布产品信息服务类
// +----------------------------------------------------------------------

namespace app\Api\system;

class ItemAddService
{
    // 敦煌网API基础URL
    const API_BASE_URL = 'http://api.dhgate.com/dop/router';

    // API版本
    const API_VERSION = '2.0';

    // API方法名
    const API_METHOD = 'dh.item.add';

    /**
     * 发布产品信息
     * @param string $accessToken 访问令牌
     * @param array $params 产品参数
     * @return array
     */
    public static function addItem($accessToken, $params)
    {
        $startTime = microtime(true);
        
        try {
            // 验证访问令牌
            if (empty($accessToken)) {
                return [
                    'success' => false,
                    'message' => '访问令牌不能为空',
                    'data' => null
                ];
            }

            // 预验证参数
            $validation = self::validateParams($params);
            if ($validation !== true) {
                return [
                    'success' => false,
                    'message' => $validation,
                    'data' => null
                ];
            }

            // 构建请求参数
            $requestParams = self::buildRequestParams($accessToken, $params);

            // 记录请求参数用于调试
            self::logApiRequest($requestParams);

            // 发送HTTP请求
            $response = self::sendHttpRequest($requestParams);

            // 解析响应
            $result = self::parseResponse($response);
            
            // 记录API响应日志
            self::logApiResponse($response, $result);
            
            // 记录整体性能
            $duration = round((microtime(true) - $startTime) * 1000, 2);
            error_log("[DHgate API] Total duration: {$duration}ms");

            return $result;
        } catch (\Exception $e) {
            error_log("[DHgate API Exception] " . $e->getMessage());
            
            return [
                'success' => false,
                'message' => '系统异常: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }

    /**
     * 验证参数
     */
    private static function validateParams($params)
    {
        // 必需参数列表
        $requiredParams = [
            'catePubId' => '发布类目ID',
            'shippingModelId' => '运费模板ID',
            'afterSaleTemplateId' => '售后模板ID',
            'itemImgList' => '产品图片列表',
            'itemBase' => '产品基础信息',
            'itemSkuList' => '产品SKU列表',
            'itemSaleSetting' => '产品销售设置',
            'itemPackage' => '产品包装信息'
        ];

        foreach ($requiredParams as $param => $name) {
            if (!isset($params[$param]) || empty($params[$param])) {
                return "缺少必需参数: {$name}({$param})";
            }
        }

        // 验证JSON格式参数
        $jsonParams = ['itemImgList', 'itemBase', 'itemSkuList', 'itemSaleSetting', 'itemPackage'];
        foreach ($jsonParams as $param) {
            if (isset($params[$param]) && is_string($params[$param])) {
                $decoded = json_decode($params[$param], true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    return "参数 {$param} JSON格式错误: " . json_last_error_msg();
                }
            }
        }

        // 验证类目ID格式
        if (!preg_match('/^\d{9,12}$/', $params['catePubId'])) {
            return '类目ID格式不正确，应为9-12位数字字符串';
        }

        return true;
    }

    /**
     * 构建请求参数
     */
    private static function buildRequestParams($accessToken, $params)
    {
        // Query参数
        $queryParams = [
            'access_token' => $accessToken,
            'timestamp' => (string)(time() * 1000),
            'method' => self::API_METHOD,
            'v' => self::API_VERSION
        ];

        // Body参数 - 业务参数
        $bodyParams = [];
        
        // 必需参数
        $requiredFields = [
            'catePubId', 'shippingModelId', 'afterSaleTemplateId',
            'itemImgList', 'itemBase', 'itemSkuList', 
            'itemSaleSetting', 'itemPackage'
        ];
        
        foreach ($requiredFields as $field) {
            if (isset($params[$field])) {
                $bodyParams[$field] = self::formatParamValue($params[$field], $field);
            }
        }
        
        // 可选参数
        $optionalFields = [
            'itemAttrList', 'itemAttrGroupList', 'itemSpecSelfDefList',
            'itemWholesaleRangeList', 'itemInventory', 'itemShiptoSettingList',
            'itemCustomTypeInfo', 'vaildDay', 'siteId', 'issample'
        ];
        
        foreach ($optionalFields as $field) {
            if (isset($params[$field]) && !empty($params[$field])) {
                $bodyParams[$field] = self::formatParamValue($params[$field], $field);
            }
        }
        
        // 设置默认值
        if (!isset($bodyParams['vaildDay'])) {
            $bodyParams['vaildDay'] = '90';
        }
        if (!isset($bodyParams['siteId'])) {
            $bodyParams['siteId'] = 'EN';
        }
        if (!isset($bodyParams['itemAttrList'])) {
            $bodyParams['itemAttrList'] = '[]';
        }
        if (!isset($bodyParams['itemAttrGroupList'])) {
            $bodyParams['itemAttrGroupList'] = '[]';
        }
        if (!isset($bodyParams['itemSpecSelfDefList'])) {
            $bodyParams['itemSpecSelfDefList'] = '[]';
        }
        if (!isset($bodyParams['itemWholesaleRangeList'])) {
            $bodyParams['itemWholesaleRangeList'] = '[]';
        }

        return [
            'query' => $queryParams,
            'body' => $bodyParams
        ];
    }
    
    /**
     * 格式化参数值
     */
    private static function formatParamValue($value, $field)
    {
        // JSON格式的字段
        $jsonFields = [
            'itemImgList', 'itemBase', 'itemSkuList', 'itemSaleSetting',
            'itemPackage', 'itemAttrList', 'itemAttrGroupList', 
            'itemSpecSelfDefList', 'itemWholesaleRangeList', 
            'itemInventory', 'itemShiptoSettingList', 'itemCustomTypeInfo'
        ];
        
        if (in_array($field, $jsonFields)) {
            if (is_array($value)) {
                return json_encode($value, JSON_UNESCAPED_UNICODE);
            } elseif (is_string($value)) {
                // 验证JSON格式
                $decoded = json_decode($value, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    return $value;
                }
            }
            return '[]'; // 默认空数组
        }
        
        return (string)$value;
    }

    /**
     * 发送HTTP请求
     */
    private static function sendHttpRequest($requestParams)
    {
        $url = self::API_BASE_URL . '?' . http_build_query($requestParams['query']);
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($requestParams['body']),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/x-www-form-urlencoded',
                'User-Agent: DHgate-API-Client/1.0'
            ]
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($response === false || !empty($error)) {
            throw new \Exception("HTTP请求失败: {$error}");
        }

        if ($httpCode !== 200) {
            throw new \Exception("HTTP状态码错误: {$httpCode}");
        }

        return $response;
    }

    /**
     * 解析响应
     */
    private static function parseResponse($response)
    {
        $data = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            return [
                'success' => false,
                'message' => 'API响应JSON格式错误: ' . json_last_error_msg(),
                'data' => null,
                'raw_response' => $response
            ];
        }

        // 检查API状态
        if (isset($data['status']['code'])) {
            if ($data['status']['code'] === '00000000') {
                return [
                    'success' => true,
                    'message' => '商品发布成功',
                    'data' => $data,
                    'item_code' => $data['itemCode'] ?? null
                ];
            } else {
                $errorMsg = $data['status']['message'] ?? '未知错误';
                $errorCode = $data['status']['code'];
                
                return [
                    'success' => false,
                    'message' => "API错误 [{$errorCode}]: {$errorMsg}",
                    'data' => $data,
                    'api_error_code' => $errorCode,
                    'solution' => self::getErrorSolution($errorCode)
                ];
            }
        }

        return [
            'success' => false,
            'message' => 'API响应格式异常',
            'data' => $data
        ];
    }

    /**
     * 获取错误解决方案
     */
    private static function getErrorSolution($errorCode)
    {
        $solutions = [
            '44' => '业务服务异常，请检查参数格式，特别是itemAttrList、catePubId、模板ID等',
            '401' => '访问令牌无效或已过期，请重新获取',
            '403' => '权限不足，请检查API权限设置',
            '1001' => '参数验证失败，请检查必需参数是否完整',
            '1002' => '类目ID不存在或格式错误',
            '1003' => '运费模板ID无效',
            '1004' => '售后模板ID无效'
        ];
        
        return $solutions[$errorCode] ?? '请联系技术支持或查看API文档';
    }

    /**
     * 记录API请求日志
     */
    private static function logApiRequest($requestParams)
    {
        $logData = [
            'method' => self::API_METHOD,
            'version' => self::API_VERSION,
            'query_params' => $requestParams['query'],
            'body_params_count' => count($requestParams['body']),
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        // 脱敏处理
        if (isset($logData['query_params']['access_token'])) {
            $logData['query_params']['access_token'] = substr($logData['query_params']['access_token'], 0, 10) . '...';
        }
        
        error_log("[DHgate API Request] " . json_encode($logData, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 记录API响应日志
     */
    private static function logApiResponse($response, $result)
    {
        $logData = [
            'success' => $result['success'],
            'response_size' => strlen($response) . ' bytes',
            'api_error_code' => $result['api_error_code'] ?? null,
            'message_preview' => mb_substr($result['message'], 0, 100, 'UTF-8'),
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        error_log("[DHgate API Response] " . json_encode($logData, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 测试API连接
     */
    public static function testApiConnection($accessToken)
    {
        try {
            $testUrl = self::API_BASE_URL . '?access_token=' . $accessToken . '&method=dh.user.get&v=2.0&timestamp=' . (time() * 1000);
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $testUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false
            ]);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode === 200) {
                return [
                    'success' => true,
                    'message' => 'API连接测试成功',
                    'http_code' => $httpCode
                ];
            } else {
                return [
                    'success' => false,
                    'message' => 'API连接测试失败，HTTP状态码: ' . $httpCode,
                    'http_code' => $httpCode
                ];
            }
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'API连接测试异常: ' . $e->getMessage()
            ];
        }
    }

    /**
     * 获取默认配置数据
     */
    public static function getDefaultConfig()
    {
        return [
            'itemBase' => [
                'itemName' => 'High Quality Fashion Women Dress Summer Casual Elegant Style',
                'shortDesc' => 'Premium fabric construction with comfortable fit and modern tailoring techniques',
                'htmlContent' => '<p>Premium fabric construction with comfortable fit and modern tailoring techniques. Made with durable materials and professional craftsmanship.</p>',
                'keyWord1' => 'Fashion',
                'keyWord2' => 'Women Dress',
                'keyWord3' => 'Summer Casual'
            ],
            'itemImgList' => [
                [
                    'imgUrl' => 'f3/albu/ys/j/25/fecd1d8e-f241-48b0-b02f-01777fe5d83d.jpg',
                    'type' => 2,
                    'imgMd5' => '72bc4eb820c469338a2db1b619770b2f'
                ],
                [
                    'imgUrl' => 'f3/albu/ys/j/25/aa9c1718-3b29-456e-bc37-4c7811b215e9.jpg',
                    'type' => 3,
                    'imgMd5' => '6813e7af8f631c177648619646fe7b07'
                ]
            ],
            'itemPackage' => [
                'grossWeight' => 0.5,
                'height' => 10,
                'length' => 10,
                'width' => 10,
                'measureId' => '00000000000000000000000000000003',
                'packingQuantity' => 1
            ],
            'itemSaleSetting' => [
                'leadingTime' => 7,
                'maxSaleQty' => 99999,
                'minWholesaleQty' => 1,
                'priceConfigType' => 1
            ],
            'itemSkuList' => [
                [
                    'inventory' => 99999,
                    'retailPrice' => '15.99',
                    'saleStatus' => 1,
                    'skuCode' => 'SKU-001',
                    'itemSkuAttrvalList' => [],
                    'itemSkuInvenList' => [
                        [
                            'skuCode' => '',
                            'saleStatus' => 1,
                            'inventoryLocation' => 'CN',
                            'skuInventoryQty' => 99999
                        ]
                    ]
                ]
            ],
            'itemWholesaleRangeList' => [
                [
                    'startQty' => 5,
                    'discount' => 0.05
                ]
            ]
        ];
    }
}
